<?php

namespace app\wechatapi\controller\user;

use app\Request;
use think\facade\Db;
use think\facade\Env;
use think\response\Json;
use app\services\user\UserServices;
use crmeb\exceptions\AdminException;
use app\services\eid\GetEidResultServices;
use app\wechatapi\controller\RestBaseController;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};


/**
 * 微信小程序授权
 * Class AdController
 * @package app\wechatapi\controller\user
 */
class OauthController extends RestBaseController
{
    /** @var UserServices */
    protected $services;

    /**
     * @return void
     */
    protected function initialize()
    {
        parent::initialize();
        $this->services = app()->make(UserServices::class);
    }

    /**
     * 微信小程序查询用户是否登录
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOpenidLogin(Request $request): Json
    {
        $data = $request->postMore([
            ['code', ''],
            ['device_type', 'wxapp'],
        ]);

        try {
            $res = $this->services->getOpenidLogin($data, $this->allowedDeviceTypes, $request->ip());
        } catch (AdminException $e) {
            $this->error($e->getMessage());
        }

        $this->success("微信小程序查询用户是否登录!", $res);
    }

    /**
     * 微信小程序授权更新用户昵称头像
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getSess(Request $request): Json
    {
        $data = $request->postMore([
            ['code', ''],
            ['encryptedData', ''],
            ['iv', '']
        ]);

        try {
            $res = $this->services->getSess($data);
        } catch (AdminException $e) {
            $this->error($e->getMessage());
        }

        $this->success("微信小程序授权成功!", $res);
    }

    /**
     * 注册师傅账号
     * @param Request $request
     * @param GetEidResultServices $getEidResultServices
     * @return Json
     */
    public function registerWorker(Request $request, GetEidResultServices $getEidResultServices): Json
    {
        $userId = $this->getUserId();
        $data = $request->postMore([
            ['EidToken', ''],
        ]);
        try {
            $getEidResultServices->registerWorker($data['EidToken'], $userId);
        } catch (AdminException $e) {
            $this->error($e->getMessage());
        }

        $this->success("注册师傅账号成功!");
    }

    public function test()
    {
        /** @var UserServices $userInfo */
        $userInfo = $this->services->getWhere(['id' => 362600392250494977]);
        halt($userInfo->toArray());
    }
}
